import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookie from 'js-cookie'

import { errPage, MenuList } from './page'

// 获取vuex中的数据
import Store from '../store'

Vue.use(VueRouter)

// 路由白名单
const whitePage = ['404', '500', 'login', 'layout', 'detail']

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../layout'),
    children: MenuList
  },
  {
    path: "/login",
    name: 'login',
    component: () => import('../views/Login')
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('../views/Detail.vue')
  },
  ...errPage
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//  登录拦截
router.beforeEach((to, from, next) => {
  const token = Cookie.get('token')

  // 获取vuex的权限字符串
  setTimeout(() => {
    const { rule } = Store.state.userInfo

    let ruleList = whitePage
    if (rule) {
      ruleList = rule.split(',')
    }

    // 将权限字符串转化为数组

    // !whitePage.some(item => item === to.path)： 过滤掉白名单中的路由，如果路由存在于白名单让其正常跳转
    if (!token && !whitePage.some(item => item === to.name)) {
      next('/login')
    } else {
      // 如果权限列表中存在 路由中的权限字段 就说明  有权限 或者是白名单中的页面  就正常跳转
      if (ruleList.some(item => item === to.meta.rule) || whitePage.some(item => item === to.name)) {
        next()
      } else {
        next('/404')
      }
    }
  }, 300)
})

export default router
